package com.atguigu.gmall.user.controller;


import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user/passport")
public class UserApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public Result login(@RequestBody UserInfo userInfo){
        //1:判断用户名或密码不能为 NULL 或 “”  “       ”  同学自行完成


        //2、进行登录判断
        UserInfo userInfo1 = userService.login(userInfo);
        //登录成功
        if (null!=userInfo1){
            //不给Map泛型，影响编译期速度，不影响运行期
            Map map =  new HashMap<>();
            //token
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            map.put("token",uuid);
            //昵称
            map.put("nickName",userInfo1.getNickName());
            redisTemplate.opsForValue().set(uuid,userInfo1.getId().toString(), RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);
        //登陆失败
        }else {
            return Result.fail().message("用户名或密码不正确");
        }
    }


    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        String token = request.getHeader("token");
        redisTemplate.delete(token);
        return Result.ok();

    }


    //根据用户ID查询收货地址集合
    @GetMapping("/userAddressList")
    public List<UserAddress> userAddressList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return userService.userAddressList(userId);
    }




}
